<template>
  <HeaderBar />
  <div class="outer-warp">
    <div class="w-full h-20 bg-white border-b">
      <div class="max-w-3xl mx-auto h-full flex items-center text-center">
        <n-icon size="40" class="mr-2">
          <paper-icon />
        </n-icon>
        <n-text class="text-2xl"> 添加科研成果 </n-text>
      </div>
    </div>
    <div class="max-w-3xl mx-auto my-5 bg-white border p-10">
      <n-space vertical class="mb-5">
        <n-steps :current="currentStep" :status="currentStepStatus">
          <n-step title="选择添加方式" />
          <n-step title="补充科研成果信息" />
          <n-step title="完成添加" />
        </n-steps>
      </n-space>
      <!-- 选择添加方式 -->
      <div class="flex flex-col" v-show="currentStep === 1">
        <div class="flex justify-center mt-3 w-1/3 mx-auto">
          <n-button
            type="primary"
            size="large"
            block
            @click="completeInfo('INPUT')"
          >
            直接信息录入
          </n-button>
        </div>
        <div class="flex justify-center mt-3 w-1/3 mx-auto">
          <n-upload
            :max="1"
            @before-upload="beforeUpload"
            :custom-request="uploadFile"
            trigger-style="width: 100%"
          >
            <n-button type="primary" size="large" block>
              RIS 文件解析
            </n-button>
          </n-upload>
        </div>
        <div class="flex justify-center mt-3 w-1/3 mx-auto">
          <n-button
            type="primary"
            size="large"
            block
            @click="completeInfo('CLAIM')"
          >
            已有成果认领
          </n-button>
        </div>
      </div>
      <!-- 补充信息 -->
      <n-spin :show="showSpin">
        <ResearchList
          v-show="currentStep === 2 && mode === 'CLAIM'"
          @claim="claim"
        />
        <ResearchForm
          v-show="currentStep === 2 && mode === 'INPUT'"
          :researchInfo="researchInfo"
          @submit="submit"
        />
      </n-spin>
      <!-- 完成添加 -->
      <div v-show="currentStep === 3">
        <n-result
          status="success"
          title="添加成功"
          :description="`将在${countDown}s后返回`"
        >
          <template #footer>
            <n-button @click="back">返回</n-button>
          </template>
        </n-result>
      </div>
    </div>
  </div>
</template>

<script setup>
import HeaderBar from '@/components/common/Headerbar.vue'
import ResearchList from '@/components/Research/ResearchList.vue'
import ResearchForm from './components/ResearchForm.vue'
import { Journal as PaperIcon } from '@vicons/ionicons5'
import api from '@/api/api'

const router = useRouter()
const message = useMessage()

const currentStep = ref(1)
const currentStepStatus = ref('process')
const mode = ref('INPUT')
const countDown = ref(5)
const countInterval = ref(null)
const showSpin = ref(false)
const researchInfo = ref({
  type: 'JOUR',
  title: '',
  authors: [],
  date: {
    year: '2022',
    month: '',
    day: ''
  },
  abstract: '',
  file: {
    url: '',
    fid: ''
  },
  other: {
    journalName: '',
    volume: '',
    issue: '',
    page: '',
    conferenceTitle: '',
    location: ''
  }
})

// 补充信息
const completeInfo = (newMode) => {
  currentStep.value = 2
  mode.value = newMode
}

// 提交
const submit = () => {
  showSpin.value = true
  api.Research.addResearch(researchInfo.value).then((res) => {
    showSpin.value = false
    if (res.success) {
      currentStep.value = 3
      currentStepStatus.value = 'finish'
      countDown.value = 5
      countInterval.value = setInterval(() => {
        if (countDown.value === 0) {
          clearInterval(countInterval.value)
          back()
        } else {
          countDown.value--
        }
      }, 1000)
    } else {
      message.error('提交失败，请重试')
    }
  })
}

// 认领
const claim = () => {
  currentStep.value = 3
  currentStepStatus.value = 'finish'
  countInterval.value = setInterval(() => {
    if (countDown.value === 0) {
      back()
    } else {
      countDown.value--
    }
  }, 1000)
}

const back = () => {
  countInterval.value && clearInterval(countInterval.value)
  const uid = localStorage.getItem('id')
  router.push({ name: 'Profile', params: { id: uid } })
}

onUnmounted(() => {
  countInterval.value && clearInterval(countInterval.value)
})

// 文件上传前检测
const beforeUpload = (data) => {
  if (data.file.file?.size > 3000000) {
    message.warning('请确保文件小于3MB')
    return false
  }
  return true
}

// 上传请求
const uploadFile = ({ file }) => {
  const formData = new FormData()
  formData.append('file', file.file)
  api.Research.risAnalysis(formData)
    .then((res) => {
      if (res.success) {
        researchInfo.value = { ...researchInfo.value, ...res.data }
        completeInfo('INPUT')
      } else {
        message.error(res.msg)
      }
    })
    .catch(() => {
      message.error('文件上传失败，请重试')
    })
}
</script>

<style scoped>
.outer-warp {
  background-color: #f4f4f4;
  min-height: calc(100vh - 73px);
  overflow: auto;
}
</style>
